#!/usr/bin/env python
# Milk.py - A wrapper for the pyrtm interface for the Remember The Milk API

__version__ = "0.1"
__author__  = "Glenn Hope"
__email__   = "hopega@email.wofford.edu"

#Imports
import milkConfig
import time
import calendar
import pprint
from rtm import createRTM, API

class Milk:
    def __init__(self, apiKey=milkConfig.apiKey, secret=milkConfig.secret, token=milkConfig.token):
        self.rtm = createRTM(apiKey, secret, token)
        #do any other loading from the config here, assign to self.


#Lists
    def getListID(self, listname):
        for lst in self.rtm.lists.getList().lists.list:
            if lst.name == listname:
                return lst.id

    def getTasks(self, list_id):
        return self.rtm.tasks.getList(list_id=list_id).tasks.list.taskseries
#Shitty shit shit shit
#        output = []
#        for task in self.rtm.tasks.getList(list_id=list_id).tasks.list.taskseries:
#            #TODO: See if there's a better way to do this (make it work for all tasks in sub-tasklist?)
#            if isinstance(task.task, (list, tuple)):
#                taskinfo = task.task[0]
#            else:
#                taskinfo = task.task
#            completed = (taskinfo.completed != "")
#
#            duedate = ""
#            if taskinfo.due != "":
#                duedate = datetime.strptime(taskinfo.due, "%Y-%m-%dT%H:%M:%SZ")
#            #TODO FIX THIS TO NOT SUCK:
#            printable = milkConfig.outputFormat % (task.name, duedate)
#            output.append(printable)
#        return output

    def printTasks(self, list_id):
        print self.getTasks(list_id)

#Tasks
    def addTask(self, taskname, list_id, smartadd=True):
        self.rtm.tasks.add(timeline=self.rtm.timelines.create().timeline,
                        name=taskname,
                        list_id = list_id,
                        parse=smartadd)

    def completeTask(self, taskname, list_id):
        self.rtm.tasks.complete(timeline=self.rtm.timelines.create().timeline,
                        list_id = list_id,
                        taskseries_id=taskname,
                        task_id=True)

    def printTaskInfo(self, list_id):
        tasklist = self.getTasks(list_id)
        for tsk in tasklist:
            printItem(tsk)
            print "----------------------------------------------------------"

#        for i, taskseries in enumerate(tasklist):
#            print "Taskseries", i
#            for key, value in taskseries.dictionary.items():
#                print key, type(value)
#                if type(value) is dict:
#                    print "  ", key
#                    if key == "notes":
#                        for note in value["note"]:
#                            for k, v in note.items():
#                                print "    ", k, "--",  [v]
#                    else:
#                        for taskkey, taskvalue in value.items():
#                            print "    ", taskkey, "--",  [taskvalue]
#                elif type(value) in (list, tuple) and key != 'tags':
#                    for i, member in enumerate(value):
#                        print "  ", key, i
#                        for ky, val in member.items():
#                            print "    ", ky, "--",  [val]
#                else:
#                    print "  ", key, "--",  [value]
#API
    def returnAPIMethods(self):
        types = API.items()
        types.sort()
        output = []
        for type, methods in types:
            cleanedMethods = []
            for method in methods.keys():
                cleanedMethods.append(method)
            output.append([type, cleanedMethods])
        return output

    def printAPIMethods(self):
        for type, methods in self.returnAPIMethods():
            print type
            for method in methods:
                print "\t", method

#Util functions
def printItem(item, inc=0):
    if str(type(item)) == "<class 'rtm.dottedDict'>":
        children = [c for c in dir(item) if not c.startswith('_')]
        for child in children:
            childvalue = item.__dict__[child]
            if str(type(childvalue)) != "<class 'rtm.dottedDict'>" \
             and type(childvalue) not in (list, tuple):
                print "%s%-15s = %s" % (" "*inc, child, childvalue)
            else:
                print " "*inc + child
            printItem(childvalue, inc+1)
    elif type(item) in (list, tuple):
        for i in item:
            printItem(i, inc+1)


#TODO: combine these into one function
def localToUTC(timestr):
    timeobj = time.strptime(timestr, '%Y-%m-%dT%H:%M:%SZ')
    convtime = time.localtime(calendar.timegm(timeobj))
    return time.strftime('%Y-%m-%dT%H:%M:%SZ', convtime)

def formatTime(timestr):
    timeobj = time.strptime(timestr, '%Y-%m-%dT%H:%M:%SZ')
    return time.strftime('%c', convtime)
